//
// Created by 11510 on 2024/7/11.
//

#ifndef REACTOR_V4_ECHOSERVER_H
#define REACTOR_V4_ECHOSERVER_H
#include "ThreadPool.h"
#include "TcpServer.h"
class MyTask {
private:
    std::string _msg;
    TcpConnection::TcpConnectionPtr _con;
public:
    MyTask(const std::string &msg, const TcpConnection::TcpConnectionPtr &con) :
            _msg(msg),
            _con(con) {}

    void process() {
        /**
         * 业务逻辑交给线程池，在此处通知线程池处理任务
         */
        printf(">>receive from client:%s", _msg.c_str());
        _con->send2loop("对不起,做不到!\n");
    }
};

class EchoServer {
private:
    ThreadPool _pool;
    TcpServer _server;
public:
    EchoServer(size_t threadNum, size_t queueSize, const std::string &ip, unsigned short port):
            _pool(threadNum, queueSize), _server(ip, port){}

    ~EchoServer() = default;

    void start(){
        _pool.start();
        using namespace std::placeholders;
        _server.setAllCallback(std::bind(&EchoServer::onNewConnection, this, _1),
                               std::bind(&EchoServer::onMessage, this, _1),
                               std::bind(&EchoServer::onClose, this, _1));
        _server.start();
    }
    void stop(){
        _server.stop();
        _pool.stop();
    }

    void onNewConnection(const TcpConnection::TcpConnectionPtr &con) {
        printf("%s has connected!!!\n", con->toString().c_str());
    }

    void onMessage(const TcpConnection::TcpConnectionPtr &con) {
        std::string msg = con->receive();

        MyTask task(msg, con);
        _pool.addTask(std::bind(&MyTask::process, &task));
    }

    void onClose(const TcpConnection::TcpConnectionPtr &con) {
        printf("%s has closed!!!\n", con->toString().c_str());
    }
};


#endif //REACTOR_V4_ECHOSERVER_H
